package com.jinzhi.jzapi.examination.task;

import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class AutomaticMarkingJob implements Job {

    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ExaminationAnswerSheetService examinationAnswerSheetService;
    @Autowired
    private ExaminationBatchService examinationBatchService;

    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("---------------------开始拆解答案计算成绩---------------------");
        //获取考试批次
      Map map = new HashMap();
      map.put("type",0);
      map.put("days", 3);
      List<ExaminationBatchDO> examinationBatchDOS = examinationBatchService.selListExamBatch(map);
      for(ExaminationBatchDO examinationBatchDO :examinationBatchDOS) {
                //根据考试批次id对应的认证批次id,查询对应的所有考生信息
                List<StuSignUpDO> stuSignUpDOS = stuSignUpService.findByKv("cbatch_id", examinationBatchDO.getCbatchId());
                if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
                    for (StuSignUpDO stuSignUpDO : stuSignUpDOS) {
                        Integer result = 0;
                        //查询到考生对应的答卷
                        
                        ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", examinationBatchDO.getId(), "state", 1);
                      //如果一个考生出现两套答卷只取其中一份答卷
                        List<ExaminationAnswerSheetDO> examinationAnswerSheetDOs = examinationAnswerSheetService
                                .findByKv("stu_sign_id", stuSignUpDO.getId(), "epaper_id", examinationPaperDO.getId());
                        ExaminationAnswerSheetDO examinationAnswerSheetDO = null;
                        if(examinationAnswerSheetDOs!=null && examinationAnswerSheetDOs.size()>0)
                        	examinationAnswerSheetDO=examinationAnswerSheetDOs.get(0);
                        List<Long> idss = examinationQuestionsService.selIdList(examinationPaperDO.getId());
                        //试卷对应的试题，有试题才算分，没有直接0分处理；
                        if(idss != null && idss.size()>0){
                            if (examinationAnswerSheetDO != null) {
                                //有答卷才算分，没有直接返回0
                                result = results(examinationAnswerSheetDO.getAnswerList(),idss);//考试总分
                            }
                        }

                        ExaminationResultsDO examinationResultsDOss = examinationResultsService
                                .findOneByKv("cbatch_id", examinationBatchDO.getCbatchId(), "ebatch_id", examinationBatchDO.getId(), "stu_sign_id", stuSignUpDO.getId());
                        if (examinationResultsDOss == null) {
                            ExaminationResultsDO examinationResultsDO = new ExaminationResultsDO();
                            examinationResultsDO.setCbatchId(stuSignUpDO.getCbatchId());//认证批次id
                            examinationResultsDO.setEbatchId(examinationPaperDO.getEbatchId());//考试批次id
                            examinationResultsDO.setStuSignId(stuSignUpDO.getId());//考生信息id
                            if(examinationAnswerSheetDO == null){
                                examinationResultsDO.setState(1);//缺考
                            }else{
                                examinationResultsDO.setState(0);//正常
                            }
                            examinationResultsDO.setTotalScore(result.doubleValue());//考试成绩
                            boolean b = examinationResultsService.insert(examinationResultsDO);
                            if (!b) {
                            	log.info("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的成绩录入失败！");
                            } else {
                                if (examinationAnswerSheetDO != null) {
                                    examinationAnswerSheetDO.setState(1);//改成已阅卷
                                    boolean c = examinationAnswerSheetService.updateById(examinationAnswerSheetDO);
                                    if (!c) {
                                    	log.info("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "答卷状态更改失败！");
                                    }
                                }

                                if (result >= examinationBatchDO.getPassMark()) {
                                    stuSignUpDO.setState(6);//状态改为理论已过
                                    boolean sbc = stuSignUpService.updateById(stuSignUpDO);
                                    if (!sbc) {
                                    	log.info("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
                                    }
                                }

                            }
                        }else {
                            if(examinationAnswerSheetDO == null){
                            	examinationResultsDOss.setState(1);//缺考
                            }else{
                            	examinationResultsDOss.setState(0);//正常
                            }
                            examinationResultsDOss.setTotalScore(result.doubleValue());//考试成绩
                            boolean b = examinationResultsService.updateById(examinationResultsDOss);
                            if (!b) {
                            	log.info("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的成绩录入失败！");
                            } else {
                                if (examinationAnswerSheetDO != null) {
                                    examinationAnswerSheetDO.setState(1);//改成已阅卷
                                    boolean c = examinationAnswerSheetService.updateById(examinationAnswerSheetDO);
                                    if (!c) {
                                    	log.info("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "答卷状态更改失败！");
                                    }
                                }

                                if (result >= examinationBatchDO.getPassMark()) {
                                    stuSignUpDO.setState(6);//状态改为理论已过
                                    boolean sbc = stuSignUpService.updateById(stuSignUpDO);
                                    if (!sbc) {
                                    	log.info("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
                                    }
                                }

                            }
                        }

                    }
                }
      }
    }


    private Integer results(String answers,List<Long> idss) {
        Integer results = 0;
        if(StringUtils.isNotBlank(answers)){
            JSONArray jsonArray2 = JSONArray.fromObject(answers);
            for(int i = 0;i<jsonArray2.size();i++){
                if(idss.indexOf(Long.parseLong(jsonArray2.getJSONObject(i).getString("id"))) > -1){
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(Long.parseLong(jsonArray2.getJSONObject(i).getString("id")));
                    if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                        if (examinationQuestionsDO.getAnswers().equals(jsonArray2.getJSONObject(i).getString("value"))) {
                            results = results + examinationQuestionsDO.getScore();
                        }
                    } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                        //String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");
                        //String answer = examinationQuestionsDO.getAnswers();
                        boolean isRight=true;
                        if(jsonArray2.getJSONObject(i).getString("value")==null||jsonArray2.getJSONObject(i).getString("value")==""){
                            isRight=false;
                        }else{
                            String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");
                            String answer = examinationQuestionsDO.getAnswers();
                            if(ssb.length!=answer.split(";;").length){
                                isRight=false;
                            }else {
                                for (int n = 0; n < ssb.length; n++) {
                                    //if (ssb[n].equals("A") || ssb[n].equals("B") || ssb[n].equals("C") || ssb[n].equals("D") || ssb[n].equals("E") || ssb[n].equals("F")) {
                                    if (!answer.contains(ssb[n])) {
                                        isRight = false;
                                        break;
                                    }

                                }
                            }
                        }

                        if (isRight) {
                            results = results + examinationQuestionsDO.getScore();
                        }

                    }
                }
            }
        }

//        String[] ssr = answers.split("\\{\"id\":\"");
//        for (int i = 1; i < ssr.length; i++) {
//            String[] ssc = ssr[i].split("\"}");
//            for (int j = 0; j < ssc.length; j++) {
//                String[] ssa = ssc[j].split("\",\"value\":\"");
//                if (ssa.length > 1) {
//                    //只有在试卷试题中的答案试题才会计算分数，为了防止其他答案重复提交；
//                    if(idss.indexOf(Long.parseLong(ssa[0])) > -1){
//                        ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(Long.parseLong(ssa[0]));
//                        if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
//                            if (examinationQuestionsDO.getAnswers().equals(ssa[1])) {
//                                results = results + examinationQuestionsDO.getScore();
//                            }
//                        } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
//                            String[] ssb = ssa[1].split(";;");
//                            String answer = "";
//                            for (int n = 0; n < ssb.length; n++) {
//                                if (answer == "") {
//                                    answer = ssb[n];
//                                } else {
//                                    answer = answer + ";;" + ssb[n];
//                                }
//                            }
//
//                            if (examinationQuestionsDO.getAnswers().equals(answer)) {
//                                results = results + examinationQuestionsDO.getScore();
//                            }
//
//                        }
//                    }
//                }
//            }
//        }

        return results;
    }

}
